package com.ccc.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.ccc.dao.LoanDao;
import com.ccc.model.Loan;
import com.ccc.util.dao.UtilDao;

@Component("loanDao")
public class LoanDaoImpl implements LoanDao {
	private UtilDao utilDao;

	@Override
	public void addLoan(Loan loan) {
		utilDao.save(loan);
	}

	@Override
	public void deleteLoan(Loan loan) {
		utilDao.delete(loan);
	}

	@Override
	public void updateLoan(Loan loan) {
		utilDao.update(loan);
	}

	@Override
	public Loan findLoan(int id) {
		return utilDao.find(Loan.class, id);
	}
	
	public List<Loan> findByLoanTime(int time) {
		return utilDao.fenye(Loan.class, -1, 1, "o.loantime=?", new Object[]{time}).getResultList();
	}

	public List<Loan> findByRepayTime(int time) {
		return utilDao.fenye(Loan.class, -1, 1, "o.repaytime=?", new Object[]{time}).getResultList();
	}

	public List<Loan> findByUserId(int userId) {
		return utilDao.fenye(Loan.class, -1, 1, "o.userId=?", new Object[]{userId}).getResultList();
	}

	public Loan findByUserIdAndLoanTime(int userId, int time) {
		List<Loan> list=utilDao.fenye(Loan.class, -1, 1, "o.userId=? and o.loantime=?", new Object[]{userId,time}).getResultList();
		if(list.size()==0){
			return null;
		}
		return list.get(0);
	}

	public Loan findByUserIdAndRepayTime(int userId, int time) {
		List<Loan> list=utilDao.fenye(Loan.class, -1, 1, "o.userId=? and o.repaytime=?", new Object[]{userId,time}).getResultList();
		if(list.size()==0){
			return null;
		}
		return list.get(0);
	}

	public void update(Loan loan) {
		utilDao.update(loan);
	}

	public List<Loan> find(int userId, int time) {
		return utilDao.fenye(Loan.class, -1, 1, "o.repaytime >= ? and loantime < ? and o.userId=?", new Object[]{time,time,userId}).getResultList();
	}

	public UtilDao getUtilDao() {
		return utilDao;
	}

	@Resource
	public void setUtilDao(UtilDao utilDao) {
		this.utilDao = utilDao;
	}

}
